﻿// Inner Fire 游戏引擎库
// DxInput DirectX输入管理器
//
// Copyright (c) 2025 by 尔西大帝. All rights reserved.
//
// 所属层级：元素层(3)
// 用于管理DirectInput
//
// Author: 尔西大帝
// Email: 2670613871@qq.com
// Created: 2025-04-26

#include "dx_input.h"

namespace ifire::dx {

DxInput::DxInput() {}

DxInput::~DxInput() {
  if (pMouse) {
    pMouse->Unacquire();
    pMouse->Release();
  }
  if (pDI) {
    pDI->Release();
  }
}

bool DxInput::Initialize(HINSTANCE hInstance, HWND hWnd) {
  // 创建DirectInput对象
  if (FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION,
          IID_IDirectInput8, (void**)&pDI, nullptr))) {
    return false;
  }

  // 创建鼠标设备
  if (FAILED(pDI->CreateDevice(GUID_SysMouse, &pMouse, nullptr))) {
    return false;
  }

  // 设置数据格式
  if (FAILED(pMouse->SetDataFormat(&c_dfDIMouse))) {
    return false;
  }

  // 设置协作级别（DISCL_NONEXCLUSIVE允许与其他程序共享）
  if (FAILED(pMouse->SetCooperativeLevel(
          hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND))) {
    return false;
  }

  // 获取设备控制权
  pMouse->Acquire();
  return true;
}
void DxInput::FixedUpdate() {
  if (pMouse) {
    // 获取鼠标状态（相对坐标模式）
    if (SUCCEEDED(pMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseState))) {
      // mouseState.lX/Y/Z 包含相对移动量
      // mouseState.rgbButtons[0-3] 包含按键状态
    }
  }
}
void DxInput::GetMouseMovement(int& deltaX, int& deltaY, int& deltaZ) const {
  deltaX = mouseState.lX;
  deltaY = mouseState.lY;
  deltaZ = mouseState.lZ;
}

bool DxInput::IsMouseButtonDown(int button) const {
  if (button >= 0 && button < 4) {
    return (mouseState.rgbButtons[button] & 0x80);
  } else {
    return false;
  }
}

} // namespace ifire::dx